package cn.xspace.module.other.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.xspace.android.imcommon.interfaces.LoginMg;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.AppManager;
import com.xspace.android.xafcommon.util.ClassUtil;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.NotifyManager;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;

import java.util.HashMap;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.OkHttpUtils;
import cn.xspace.library.util.Tools;
import cn.xspace.module.other.R;
import cn.xspace.module.other.application.MyApplication;
import cn.xspace.module.other.http.impl.ResetPasswordImpl;
import cn.xspace.module.other.http.impl.ResetPasswordImpl.IResetPasswordMg;
import cn.xspace.module.other.util.RProxy;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class ReSetPwdAct extends BaseActivity {
    private EditText new_pwd, new_pwd_ok, old_pwd;
    private NotEmptyTextWatcher mTextWatcher = new NotEmptyTextWatcher();
    private Context mContext;

    /**
     * 正在提交
     */
    public static final int PROGRESS_STATUS_REGISTER = 2;
    String mUserName = "";
    String result = "";
    private TitleBar titleBar;
    private String userId;
    private String user_mobile;
    private String newPwd;
    private String newPwd_ok;
    private String oldPwd;

    @Override
    protected void initView() {
        setContentView(R.layout.resetpwdact);
        String prefernces_name = (String) PreferencesUtils.getPfValue(
                ReSetPwdAct.this, Constants.ACCOUNT_BAREJID_KEY,
                String.class.getName());
        if (prefernces_name != null) {
            mUserName = prefernces_name.split("@")[0];
        }
    }

    @Override
    protected void initData() {
        user_mobile = getIntent().getStringExtra("user_mobile");
        mContext = this;
    }

    @Override
    protected void initFindViewById() {
        old_pwd = (EditText) findViewById(RProxy.old_pwd);
        old_pwd.addTextChangedListener(mTextWatcher);
        new_pwd = (EditText) findViewById(RProxy.set_new_pwd);
        new_pwd.addTextChangedListener(mTextWatcher);
        new_pwd_ok = (EditText) findViewById(RProxy.new_pwd_setok);
        new_pwd_ok.addTextChangedListener(mTextWatcher);
        titleBar = (TitleBar) findViewById(R.id.resetpwd_title_bar);
    }

    @Override
    protected void initEvent() {
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void onClick(View v) {
        /*if (v.getId() == RProxy.resetpwd_cb) {
            CheckBox cb = (CheckBox) findViewById(RProxy.resetpwd_cb);
            if (cb.isChecked()) {
                old_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                new_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                new_pwd_ok.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                old_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                new_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                new_pwd_ok.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        } else */
        if (v.getId() == R.id.reset_pwd) {
            oldPwd = old_pwd.getText().toString().trim();
            newPwd = new_pwd.getText().toString().trim();
            newPwd_ok = new_pwd_ok.getText().toString().trim();
            if (oldPwd.equals(newPwd)) { //新旧密码相同
                showErrorDialog(getString(R.string.new_and_old_pwd_equal));
                new_pwd_ok.setText("");
                new_pwd.setText("");
            }
            if (!newPwd.equals(newPwd_ok)) {   // 两次密码不一致
//                Toast.makeText(
//                        getApplicationContext(),
//                        RProxy.registeract_confirm_password_edttxt_passwords_not_equal,
//                        Toast.LENGTH_SHORT).show();
                showErrorDialog(getString(R.string.pwd_no_equal));
                new_pwd_ok.setText("");
                return;
            }
            if (!checkPasswordLength()) {    //密码不能少于六位数
                new_pwd.setError(String
                        .format(getString(RProxy.registeract_password_edttxt_passwords_too_short),
                                "6"));
                return;
            }
//            reSetPwd(pwd, old_pwd.getText().toString());
            changeUserPwd();
        }

    }

    // 显示错误提示
    private void showErrorDialog(String error) {
        new ConfirmDialog.Builder(mContext)
                .setContentMsg(error)
                .setLeftText(getString(R.string.exit))
                .setRightButtonGone()
                .setMaxLine(3)
                .setListener()
                .setTitleVisible(View.GONE)
                .show();
    }

    private void exitApp() {
        NotifyManager.cancelAll(ReSetPwdAct.this);
        PreferencesUtils.setPfValue(ReSetPwdAct.this,
                Constants.ACCOUNT_VALIDATED, "0", String.class.getName());
        Tools.sendStopServiceBroadcast(ReSetPwdAct.this);
        Tools.sendExitAppBroadcast(ReSetPwdAct.this);
        LoginMg.getInstance().userLogout();
    }

    public void reSetPwd(String newPwd_MD5, String oldPwd_MD5) {


        new ResetPasswordImpl(this).reSetPassword(Tools.getCurrentAccountInfo(this).mobile, newPwd_MD5, oldPwd_MD5,
                new IResetPasswordMg() {

                    @Override
                    public void onCallBack(boolean flag) {
                        if (flag) {
                            //重置密码之后不再退出程序,而是清除用户数据,弹出登录界面
                            Tools.exitApp(getBaseContext());
                            BldNavigation.HxXmppLoginout(mContext);
                            //增加退出重打开主页
                            AppManager.getAppManager().finishAllActivity();
                            gotoHomeAct();

//                            //清除用户数据
//                            Tools.logoutAndClearData(getBaseContext());
                            PreferencesUtils.setPfValue(getBaseContext(),
                                    Constants.ACCOUNT_PASSWORD_KEY, "", String.class.getName());
                            HashMap<String, Object> inParam = new HashMap<>();
                            inParam.put(EventBusConstant.TYPE, UserInfoAct.TAG);
                            inParam.put(EventBusConstant.ACTION_KEY, EventBusConstant.LONGIN_OUT);
                            EventBus.getDefault().post(inParam);

                        } else {

                        }
                    }
                });
    }

    /**
     * 前往主页
     */
    private void gotoHomeAct() {
        Log.e("wubaojie--", "gotoHomeAct" + "准备首页");
        Intent intent = new Intent();
//        intent.setClassName(MyApplication.get(), "cn.xspace.app.activity.OfflineWebView");
        // 打开登录界面
        intent.setClassName(MyApplication.get(), ClassUtil.LOGIN_CLASS);
        startActivity(intent);
        finish();
    }

    private boolean checkPasswordLength() {
        CharSequence password = new_pwd.getText();
        return password.length() >= 6;
    }

    /**
     * Text watcher to test if all fields are field.
     */
    private class NotEmptyTextWatcher implements TextWatcher {

        /**
         * Constructor.
         */
        public NotEmptyTextWatcher() {
        }

        @Override
        public void afterTextChanged(Editable s) {
            boolean enable = !(TextUtils.isEmpty(mUserName)
                    || TextUtils.isEmpty(new_pwd.getText()) || TextUtils
                    .isEmpty(old_pwd.getText()));
            findViewById(R.id.reset_pwd).setEnabled(enable);

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }
    }

    private void changeUserPwd() {
        final Map<String, Object> map = new HashMap<>();
        map.put("user_mobile", user_mobile);  // 手机号
        map.put("user_newpwd", newPwd); // 新密码
        map.put("user_oldpwd", oldPwd); // 旧密码
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.UPDATE_USER_PWD, map);
                if (OkHttpUtils.isSuccess(bean)) {
                    LogUtil.e("ReSetPwdAct     =======     返回结果成功");
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                showErrorDialog(getString(R.string.old_pwd_error));
                throwable.printStackTrace();
            }

            @Override
            public void onNext(Object result) {
                if (result != null) {
                    LogUtil.e("ReSetPwdAct     =======     返回结果 " + ((BaseReturnBean) result).desc);
                    T.showSingleL("密码修改成功");
                    //重置密码之后不再退出程序,而是清除用户数据,弹出登录界面
                    Tools.exitApp(getBaseContext());
                    BldNavigation.HxXmppLoginout(mContext);
                    //增加退出重打开主页
                    AppManager.getAppManager().finishAllActivity();
                    gotoHomeAct();

//                  清除用户数据
//                  Tools.logoutAndClearData(getBaseContext());
                    PreferencesUtils.setPfValue(getBaseContext(),
                            Constants.ACCOUNT_PASSWORD_KEY, "", String.class.getName());
                    HashMap<String, Object> inParam = new HashMap<>();
                    inParam.put(EventBusConstant.TYPE, UserInfoAct.TAG);
                    inParam.put(EventBusConstant.ACTION_KEY, EventBusConstant.LONGIN_OUT);
                    EventBus.getDefault().post(inParam);
                }
            }
        });

    }

}
